#include "los_task.h"
#include "ohos_init.h"
#include "picture.h"
#include "lcd.h"
#include "sht30.h"
#include "iot_errno.h"
#include "iot_pwm.h"
#include "iot_gpio.h"
#include <stdio.h>
#include "cmsis_os.h"
#include "config_network.h"
#include <stdbool.h>
#include "iot.h"
#include "cmsis_os2.h"  // LiteOS-M 的 OS API
#include "lwip/sockets.h"  // lwIP socket API
#include "mq2.h"
#include "smart_pill_event.h"
#include <sys/time.h>
#include "eeprom.h"
#include "los_swtmr.h"
#include "iot_i2c.h"
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
#include <netdb.h>  // 解决gethostbyname声明问题
#include "los_mux.h"
#include "bh1750.h"

#define EEPROM_TIME_MAX_LEN 32

static time_t alarm_start_time = 0;
// 全局时间变量和互斥锁
UINT32 g_timeMutexId;
static volatile bool g_time_valid = false; // 时间是否有效的标志

// 新增NTP同步任务
#define NTP_SYNC_INTERVAL 60 // 1小时同步一次


#define MAX_ALARMS 5
void format_time(char* buffer, size_t size) {
    time_t now = time(NULL);
    if (now < 1577836800) { // 小于2020年，则视为未同步
        snprintf(buffer, size, "--:--:--");
    } else {
        struct tm timeinfo;
        localtime_r(&now, &timeinfo);
        strftime(buffer, size, "%H:%M:%S", &timeinfo);
    }
}


// Simple NTP packet structure
typedef struct {
    uint8_t flags;
    uint8_t stratum;
    uint8_t poll_interval;
    uint8_t precision;
    uint32_t root_delay;
    uint32_t root_dispersion;
    uint32_t ref_id;
    uint32_t ref_timestamp[2];
    uint32_t originate_timestamp[2];
    uint32_t receive_timestamp[2];
    uint32_t transmit_timestamp[2];
} ntp_packet;


#define EEPROM_I2C_PORT EI2C0_M2

#define ROUTE_SSID      "123456789"          // WiFi账号
#define ROUTE_PASSWORD "1234567890"       // WiFi密码

#define NTP_PORT 123
#define NTP_TIMESTAMP_DELTA 2208988800ULL // 添加 ULL 后缀

#define MSG_QUEUE_LENGTH                                16
#define BUFFER_LEN                                      50



 
extern const unsigned char gImage_isoftstone[IMAGE_MAXSIZE_ISOFTSTONE];

/* RGB对应的PWM通道 */
#define LED_R_PORT EPWMDEV_PWM1_M1
#define LED_G_PORT EPWMDEV_PWM7_M1
#define LED_B_PORT EPWMDEV_PWM0_M1


/* 电机对应PWM */
#define ELECTRICAL_MACHINERY_PORT EPWMDEV_PWM6_M0
/* 蜂鸣器对应PWM */
#define BEEP_PORT EPWMDEV_PWM5_M0
/*LED对应的口*/
#define GPIO_TEST     GPIO0_PA5

char receive_time_str[32] = {0};


extern void notify_mqtt_connected(void);


static bool g_mqtt_connected = false;
static int motor_running = 0; // 控制电机状态
double bh1750_data = 0.0;
static float humidity;
static float temperature;
float ppm;
static int alarmFlag  = 0;
static int alarmFlag_daojishi = 0;

int g_countdown_time;
bool g_countdown_valid = false;
int time_display;
int once;




char stored_times[MAX_TIME_GROUP][EEPROM_TIME_MAX_LEN];


void smart_home_iot_cmd_process(int iot_cmd)
{
    switch (iot_cmd)
    {
        case IOT_CMD_MOTOR_ON:
            motor_running = 1;
            break;
        case IOT_CMD_MOTOR_OFF:
            motor_running = 0;
            break;
    }
}

int get_motor_state(void)
{
    return motor_running;
}

void notify_mqtt_connected(void) {
    g_mqtt_connected = true;
}

void smart_pill_home_cmd_process(int iot_cmd)
{
    switch (iot_cmd)
    {
        case IOT_CMD_MOTOR_ON:
            motor_running = 1;
            break;
        case IOT_CMD_MOTOR_OFF:
            motor_running = 0;
            break;
    }
}
 void iot_thread(void *args) {
    uint8_t mac_address[12] = {0x00, 0xdc, 0xb6, 0x90, 0x01, 0x00,0};
    char ssid[32]=ROUTE_SSID;
    char password[32]=ROUTE_PASSWORD;
    char mac_addr[32]={0};
  
    FlashDeinit();
    FlashInit();
  
    VendorSet(VENDOR_ID_WIFI_MODE, "STA", 3); // 配置为Wifi STA模式
    VendorSet(VENDOR_ID_MAC, mac_address, 6); // 多人同时做该实验，请修改各自不同的WiFi MAC地址
    VendorSet(VENDOR_ID_WIFI_ROUTE_SSID, ssid, sizeof(ssid));
    VendorSet(VENDOR_ID_WIFI_ROUTE_PASSWD, password,sizeof(password));
  
  reconnect:
    SetWifiModeOff();
    int ret = SetWifiModeOn();
    if(ret != 0){
      printf("wifi connect failed,please check wifi config and the AP!\n");
      return;
    }
    mqtt_init();
    if (!wait_message()) {
        goto reconnect;
    }
    printf("MQTT connected successfully\n");
    notify_mqtt_connected(); // 触发 NTP 同步开始
  
    while (1) {
      if (!wait_message()) {
        goto reconnect;
      }
      LOS_Msleep(1);
    }
}
 
 void lcd_process(void *arg)
 {
     uint32_t ret = 0;
     uint8_t cur_sizey = 12;
     
     
     ret = lcd_init();
     if (ret != 0)
     {
         printf("lcd_init failed(%d)\n", ret);
         return;
     }
     
     lcd_fill(0, 0, LCD_W, LCD_H, LCD_WHITE);
     while (1)
     {
        // 在lcd_process的while循环中添加
         char time_str[32] = {0};
         format_time(time_str, sizeof(time_str));
         lcd_show_string(180, 200, time_str, LCD_RED, LCD_GRAY, 24,0);
         lcd_show_picture(20, 140, 40, 40, gImage_huminity);
         lcd_show_picture(20, 60, 40, 40, gImage_temperature);
         lcd_show_picture(150, 60, 40, 40, gImage_lux);
         
    

         if(alarmFlag  == 1||alarmFlag_daojishi ==1)
         {
            lcd_show_picture(290, 210, 20, 20, gImage_alarm);
         }
         else
         {
            lcd_show_picture(290, 210, 20, 20, gImage_alarm_display);
         }
         if(g_countdown_valid == true)
         {
            lcd_show_chinese(205, 120,(uint8_t *)"倒计时" , LCD_RED, LCD_GRAY, 16, 0);
            if(time_display <60)
            {
                lcd_show_int_num(205, 150, time_display, 2, LCD_RED, LCD_GRAY, 24);
                lcd_show_chinese(240, 150,(uint8_t *)"秒" , LCD_RED, LCD_GRAY, 24, 0);
            }
            else if(time_display >= 60&&time_display <3600)
            {
                lcd_show_int_num(205, 150, time_display/60, 2, LCD_RED, LCD_GRAY, 24);
                lcd_show_chinese(240, 150,(uint8_t *)"分" , LCD_RED, LCD_GRAY, 24, 0);
            }
            else
            {
                lcd_show_int_num(205, 150, time_display/3600, 2, LCD_RED, LCD_GRAY, 24);
                lcd_show_chinese(240, 150,(uint8_t *)"时" , LCD_RED, LCD_GRAY, 24, 0);
            }
         }
         else
         {
            lcd_fill(205,150,270,180,LCD_WHITE);
         }
         lcd_show_chinese(30, 15,(uint8_t *)"欢迎使用智能药盒系统" , LCD_RED, LCD_GRAY, 24, 0);
         lcd_show_chinese(24, 104,(uint8_t *)"温度" , LCD_RED, LCD_GRAY, 16, 0);
         lcd_show_chinese(24, 184,(uint8_t *)"湿度" , LCD_RED, LCD_GRAY, 16, 0);

         lcd_show_float_num1(75, 75, temperature, 4,LCD_RED, LCD_GRAY, 24);
         lcd_show_float_num1(75, 155, humidity, 4,LCD_RED, LCD_GRAY, 24);
         lcd_show_float_num1(205, 75, bh1750_data, 5,LCD_RED, LCD_GRAY, 24);

         if (cur_sizey == 12)
             cur_sizey = 16;
         else if(cur_sizey == 16)
             cur_sizey = 24;
         else if(cur_sizey == 24)
             cur_sizey = 32;
         else
             cur_sizey = 12;
 
         LOS_Msleep(100);
     }
 }
void sht30_proress(void *arg)
{
    double sht30_data[2] = {0};

    /* 初始化sht30 */
    sht30_init();
    /* 初始化bh1750 */
    bh1750_init();

    while (1)
    {
        /* 读取sht30数据 */
        sht30_read_data(sht30_data);
        temperature = sht30_data[0];
        humidity = sht30_data[1];

        /* 读取bh1750数据 */
        bh1750_read_data(&bh1750_data);
        LOS_Msleep(1000);
    }
}


void timer1_timeout(void *arg)
{
    g_countdown_valid = false;
    timer_example();
    alarmFlag_daojishi = 1;
}


void timer2_timeout(void *arg)
{
    alarmFlag_daojishi = 0;
}

void timer3_timeout(void *arg)
{
    if (alarmFlag_daojishi == 0)
    {
        if (time_display > 0&&once == 0)
        {
            time_display--;
            printf("⏱ 倒计时中：%d 秒\n", time_display);
            timer3_example();
        }

        if (time_display <= 0)
        {
            printf("✅ 倒计时结束\n");
        }
    }
}


void timer4_timeout(void *arg)
{
    motor_running = 0;
}


void timer4_example(void)
{
    unsigned int timer_id4;
    unsigned int ret;
    ret = LOS_SwtmrCreate(3000, LOS_SWTMR_MODE_ONCE, timer4_timeout, &timer_id4, NULL);
    if (ret == LOS_OK)
    {
        ret = LOS_SwtmrStart(timer_id4);
        if (ret != LOS_OK)
        {
            printf("start timer4 fail ret:0x%x\n", ret);
            return;
        }
    }
}

void timer3_example(void)
{ 
    unsigned int timer_id3;
    unsigned int ret;
    ret = LOS_SwtmrCreate(1000, LOS_SWTMR_MODE_ONCE, timer3_timeout, &timer_id3, NULL);
    if (ret == LOS_OK)
    {
        ret = LOS_SwtmrStart(timer_id3);
        if (ret != LOS_OK)
        {
            printf("start timer3 fail ret:0x%x\n", ret);
            return;
        }
    }
     else
    {
        printf("create timer3 fail ret:0x%x\n", ret);
        return;
    }
}

void timer_example()
{
    unsigned int timer_id1;
    unsigned int timer_id2;
    unsigned int ret;
    if(g_countdown_valid)
    {
        ret = LOS_SwtmrCreate(g_countdown_time*1000, LOS_SWTMR_MODE_ONCE, timer1_timeout, &timer_id1, NULL);
        if (ret == LOS_OK)
        {
            ret = LOS_SwtmrStart(timer_id1);
            if (ret != LOS_OK)
            {
                printf("start timer1 fail ret:0x%x\n", ret);
                return;
            }
        }
        else
        {
            printf("create timer1 fail ret:0x%x\n", ret);
            return;
        }
    }
    else{
        ret = LOS_SwtmrCreate(5000, LOS_SWTMR_MODE_ONCE, timer2_timeout, &timer_id2, NULL);
        if (ret == LOS_OK)
        {
            ret = LOS_SwtmrStart(timer_id2);
            if (ret != LOS_OK)
            {
                printf("start timer2 fail ret:0x%x\n", ret);
                return;
            }
        }
        else
        {
            printf("create timer2 fail ret:0x%x\n"), ret;
            return;
        }
    }
}


void beep_process()
{
    unsigned int ret;
    unsigned int duty = 80;
    /* 初始化PWM */
    ret = IoTPwmInit(BEEP_PORT);
    if (ret != 0) {
        printf("IoTPwmInit failed(%d)\n", BEEP_PORT);
    }
    while (1)
    {
        if(alarmFlag  == 1||alarmFlag_daojishi == 1)
        {
            printf("PWM(%d) Start\n", BEEP_PORT);
            /* 开启PWM */
            ret = IoTPwmStart(BEEP_PORT, duty, 1000);
            if (ret != 0) {
                printf("IoTPwmStart failed(%d)\n");
                continue;
            }
            LOS_Msleep(1000);
        }
        else if(alarmFlag  == 0||alarmFlag_daojishi == 0)
        {
            /* 关闭PWM */
            ret = IoTPwmStop(BEEP_PORT);
            if (ret != 0) {
                printf("IoTPwmStart failed(%d)\n");
                continue;
            }
            LOS_Msleep(1000);
        }
    }
}
void gpio_demo(){
    printf("gpio_demo start\n");
    //初始化IO口
    IoTGpioInit(GPIO_TEST);
    //设置GPIO为输出方向
    IoTGpioSetDir(GPIO_TEST, IOT_GPIO_DIR_OUT);
    if(alarmFlag  == 0||alarmFlag_daojishi == 0)
    {
    //设置GPIO输出电平
        IoTGpioSetOutputVal(GPIO_TEST, IOT_GPIO_VALUE0);
    }
    else
    {
    //设置GPIO输出电平
        IoTGpioSetOutputVal(GPIO_TEST, IOT_GPIO_VALUE1);
    }
    LOS_Msleep(1000);
}

APP_FEATURE_INIT(gpio_demo);

void rgb_led_process()
{
    unsigned int ret;
    /* 初始化PWM */
    ret = IoTPwmInit(LED_R_PORT);
    if (ret != 0) {
        printf("IoTPwmInit failed(%d)\n", LED_R_PORT);
    }
    ret = IoTPwmInit(LED_G_PORT);
    if (ret != 0) {
        printf("IoTPwmInit failed(%d)\n", LED_G_PORT);
    }
    ret = IoTPwmInit(LED_B_PORT);
    if (ret != 0) {
        printf("IoTPwmInit failed(%d)\n", LED_B_PORT);
    }
    while (1)
    {
        if(alarmFlag  == 0||alarmFlag_daojishi == 0)
        {
            /* 关闭 RGB 灯：将占空比设置为 0 */
            IoTPwmStop(LED_R_PORT);
            IoTPwmStop(LED_G_PORT);
            IoTPwmStop(LED_B_PORT);
            LOS_Msleep(200); // 避免频繁检查 alarm
        }
        else if(alarmFlag  == 1||alarmFlag_daojishi == 1)
        { 
            /* 显示红色：红灯占空比为 100%，绿灯和蓝灯占空比为 0 */
            IoTPwmStart(LED_R_PORT, 99, 1000); // 红灯占空比 100%
            IoTPwmStop(LED_G_PORT);
            IoTPwmStop(LED_B_PORT);
            LOS_Msleep(200); // 避免频繁检查 alarm
        }
    }
}

void smart_home_thread(void *arg)
{
    e_iot_data iot_data = {0};
    while(1)
    {
        event_info_t event_info = {0};
        //等待事件触发,如有触发,则立即处理对应事件,如未等到,则执行默认的代码逻辑,更新屏幕
        int ret = smart_home_event_wait(&event_info,3000);
        if(ret == LOS_OK){
            //收到指令
            printf("event recv %d ,%d\n",event_info.event,event_info.data.iot_data);
            switch (event_info.event)
            {
                case event_iot_cmd:
                    smart_home_iot_cmd_process(event_info.data.iot_data);
                    break;
                case event_countdown:
                    g_countdown_time = event_info.data.param;
                    g_countdown_valid = true; // 接收到有效倒计时，开启标志
                    time_display = g_countdown_time;  // ← 初始化一次
                    printf("g_countdown_valid:%d",g_countdown_valid);
                    printf("⏱ 收到倒计时指令：%d 秒\n", g_countdown_time);
                    timer_example(); // 触发定时器创建与启动
                    timer3_example();
                    // 可以在这里触发执行倒计时操作
                    break;
               default:break;
            }
        }
        if (mqtt_is_connected()) 
        {
            // 发送iot数据
            iot_data.illumination = bh1750_data;
            iot_data.temperature = temperature;
            iot_data.humidity = humidity;
            iot_data.motor_state = (bool)get_motor_state();
            iot_data.ppm = ppm;
            // iot_data.auto_state = auto_state;
            send_msg_to_mqtt(&iot_data);
            
        }
    }
}


void test_udp_socket(void) {
    int sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (sockfd < 0) {
        printf("Socket creation failed, errno=%d\n", errno);
        return;
    }
    printf("UDP socket created successfully\n");
    close(sockfd);
}



int get_ntp_time(const char* hostname) {
    int sockfd = -1;
    struct sockaddr_in servaddr = {0};

    sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (sockfd < 0) {
        printf("Socket creation failed: %s\n", strerror(errno));
        return -1;
    }

    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(NTP_PORT);

    if (inet_aton("202.120.2.101", &servaddr.sin_addr) == 0) {
        printf("Invalid NTP server IP\n");
        goto cleanup;
    }

    ntp_packet packet = {0};
    packet.flags = 0x1B;

    socklen_t addr_len = sizeof(servaddr);
    if (sendto(sockfd, &packet, sizeof(packet), 0, (struct sockaddr *)&servaddr, addr_len) < 0) {
        perror("Send failed");
        goto cleanup;
    }

    printf("NTP request sent to %s\n", hostname);

    struct timeval timeout = {2, 0};
    setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));

    ntp_packet response;
    ssize_t n = recvfrom(sockfd, &response, sizeof(response), 0, (struct sockaddr *)&servaddr, &addr_len);

    if (n < sizeof(ntp_packet)) {
        printf("NTP response too short\n");
        goto cleanup;
    }

    uint32_t ntp_seconds = ntohl(response.transmit_timestamp[0]);
    uint64_t secs_since_1900 = (uint64_t)ntp_seconds;

    if (secs_since_1900 < NTP_TIMESTAMP_DELTA) {
        printf("Invalid NTP time: %llu\n", secs_since_1900);
        goto cleanup;
    }

    time_t new_time = (time_t)(secs_since_1900 - NTP_TIMESTAMP_DELTA);

    struct timeval tv = {
        .tv_sec = new_time,
        .tv_usec = 0
    };
    settimeofday(&tv, NULL);
    time_t now = time(NULL);
    printf("[DEBUG] Time after settimeofday: %ld\n", now);

    g_time_valid = true;
    printf("NTP Sync Success: %ld\n", (long)new_time);

cleanup:
    if (sockfd >= 0) {
        close(sockfd);
    }
    return 0;
}



void ntp_sync_task(void *arg) {
    const char* ntp_server = "ntp.ntsc.ac.cn";
    int retry_count = 0;
    const int max_retry = 3;
    const int retry_interval = 10000; // 重试间隔改为 10 秒
    printf("NTP sync task started\n");
    while (1) {
        if (g_mqtt_connected) {
            printf("Trying NTP sync (attempt %d)...\n", retry_count + 1);
            if (get_ntp_time(ntp_server) == 0) {
                printf("NTP sync success\n");
                retry_count = 0; // 重置计数器
                break; // 成功则退出循环
            } else {
                retry_count++;
                g_mqtt_connected = true;
                if (retry_count >= max_retry) {
                    printf("NTP sync failed after %d retries\n", max_retry);
                    retry_count = 0;
                }
                LOS_Msleep(retry_interval); // 增加间隔
            }
        }
        LOS_Msleep(1000); // 主循环检查频率降低
    }
    // 后续每小时同步一次
    while (1) {
        LOS_Msleep(1000 * 3600);
        g_mqtt_connected = false;
        get_ntp_time(ntp_server);
        g_mqtt_connected = true;
    }
}

void gas_sensor_process() 
{
  /* 初始化mq2设备 */
  mq2_dev_init();

  LOS_Msleep(1000);

  /* 传感器校准 */
  mq2_ppm_calibration();

  while (1) 
  {
    /*获取电压值*/
    ppm = get_mq2_ppm();

    /* 睡眠1秒 */
    LOS_Msleep(1000);
  }
}


void electrical_machinery_process()
{
    unsigned int ret;

    /* 初始化PWM */
    ret = IoTPwmInit(ELECTRICAL_MACHINERY_PORT);
    if (ret != 0) {
        printf("IoTPwmInit failed(%d)\n", ELECTRICAL_MACHINERY_PORT);
    }

    while (1)
    {
        if(motor_running)
        {
            /* 开启PWM */
            ret = IoTPwmStart(ELECTRICAL_MACHINERY_PORT, 12, 50);
            if (ret != 0) {
                printf("IoTPwmStart failed(%d)\n");
                continue;
            }
            timer4_example();
        }
        else
        {
            /* 关闭PWM */
            ret = IoTPwmStart(ELECTRICAL_MACHINERY_PORT, 3, 50);
            if (ret != 0) {
                printf("IoTPwmStart failed(%d)\n");
                continue;
            }
        }
        LOS_Msleep(1000);
    }
}


// 定义时间比对线程入口函数
// void time_compare_thread(void *arg) {
//     (void)arg;
//     while (!g_time_valid) {
//         LOS_Msleep(1000);
//     }

//     PillTime alarm_times[MAX_ALARMS];
//     int last_trigger_minute = -1;

//     while (1) {
//         time_t now = time(NULL);
//         struct tm current_time;
//         localtime_r(&now, &current_time);

//         for (int i = 0; i < MAX_ALARMS; i++) {
//             unsigned int addr = EEPROM_TIME_START_ADDR + i * sizeof(PillTime);
//             if (eeprom_read(addr, (uint8_t *)&alarm_times[i], sizeof(PillTime)) != sizeof(PillTime)) {
//                 continue;
//             }
//         }

//         for (int i = 0; i < MAX_ALARMS; i++) {
//             if (alarm_times[i].hour == 0xFF || alarm_times[i].minute == 0xFF) {
//                 continue;
//             }
//             printf("系统时间: %02d:%02d，对比闹钟[%d]: %02d:%02d\n",
//                    current_time.tm_hour, current_time.tm_min,
//                    i, alarm_times[i].hour, alarm_times[i].minute);

//             if (current_time.tm_hour == alarm_times[i].hour &&
//                 current_time.tm_min == alarm_times[i].minute &&
//                 last_trigger_minute != current_time.tm_min) {
//                 last_trigger_minute = current_time.tm_min;
//                 printf("🔔 Alarm %d Triggered at %02d:%02d\n", i,
//                        alarm_times[i].hour, alarm_times[i].minute);
//                 alarmFlag = 1;
//             }
//             // 超时自动清除报警
//             if (alarmFlag == 1 && (now - alarm_start_time) >= 60) {
//                 alarmFlag = 0;
//                 printf("⏹ 报警结束\n");
//             }
//         }

//         LOS_Msleep(30000);
//     }
// }

// 时间比对线程
void time_compare_thread(void *arg) {
    (void)arg;
    while (!g_time_valid) {
        LOS_Msleep(1000);
    }

    PillTime alarm_times[MAX_ALARMS];
    int last_trigger_minute[MAX_ALARMS] = {-1, -1, -1, -1, -1};
    static time_t alarm_start_time = 0;

    while (1) {
        time_t now = time(NULL);
        struct tm current_time;
        localtime_r(&now, &current_time);

        for (int i = 0; i < MAX_ALARMS; i++) {
            unsigned int addr = EEPROM_TIME_START_ADDR + i * sizeof(PillTime);
            if (eeprom_read(addr, (uint8_t *)&alarm_times[i], sizeof(PillTime)) != sizeof(PillTime)) {
                continue;
            }
            if (alarm_times[i].hour == 25 && alarm_times[i].minute == 0) {
                continue;
            }
            printf("系统时间: %02d:%02d，对比闹钟[%d]: %02d:%02d\n",
                   current_time.tm_hour, current_time.tm_min,
                   i, alarm_times[i].hour, alarm_times[i].minute);

            if (current_time.tm_hour == alarm_times[i].hour &&
                current_time.tm_min == alarm_times[i].minute &&
                last_trigger_minute[i] != current_time.tm_min) {

                last_trigger_minute[i] = current_time.tm_min;
                alarm_start_time = now;
                alarmFlag = 1;
                printf("🔔 Alarm %d Triggered at %02d:%02d\n", i,
                       alarm_times[i].hour, alarm_times[i].minute);
            }
        }

        // 超时自动清除报警
        if (alarmFlag == 1 && (now - alarm_start_time) >= 30) {
            alarmFlag = 0;
            printf("⏹ 报警结束\n");
        }

        LOS_Msleep(10000);
    }
}




void smart_pill_box()
{
    smart_home_event_init();
    g_timeMutexId = LOS_MuxCreate(NULL); // 参数为 NULL 表示系统自动分配资源
    if (g_timeMutexId == LOS_ERRNO_MUX_INVALID) {
        printf("Failed to create mutex\n");
    }
    // 在程序初始化时设置（如main或smart_pill_box）
    setenv("TZ", "Asia/Shanghai", 1); // 替换原有代码
    tzset();

    if(IoTI2cInit(EEPROM_I2C_PORT, EI2C_FRE_100K) != IOT_SUCCESS) {
        printf("%s, %s, %d: I2c init failed!\n", __FILE__, __func__, __LINE__);
        return IOT_FAILURE;
    }
    eeprom_init_ptr(); // 加载写入指针

    char stored_time[EEPROM_TIME_MAX_LEN];
     
    if (eeprom_read_time(stored_time, sizeof(stored_time)) == IOT_SUCCESS) {
        strncpy(receive_time_str, stored_time, sizeof(receive_time_str) - 1);
        receive_time_str[sizeof(receive_time_str) - 1] = '\0';
        printf("Restored time from EEPROM: %s\n", receive_time_str);
    } else {
        printf("No valid time in EEPROM\n");
        receive_time_str[0] = '\0'; // 清空时间
    }

    unsigned int thread_id_1;
    unsigned int thread_id_2;
    unsigned int thread_id_3;
    unsigned int thread_id_4;
    unsigned int thread_id_5;
    unsigned int thread_id_6;
    unsigned int thread_id_7;
    unsigned int thread_id_8;
    unsigned int thread_id_9;
    unsigned int thread_id_10;
    unsigned int thread_id_11;

    TSK_INIT_PARAM_S task_1 = {0};
    TSK_INIT_PARAM_S task_2 = {0};
    TSK_INIT_PARAM_S task_3 = {0};
    TSK_INIT_PARAM_S task_4 = {0};
    TSK_INIT_PARAM_S task_5 = {0};
    TSK_INIT_PARAM_S task_6 = {0};
    TSK_INIT_PARAM_S task_7 = {0};
    TSK_INIT_PARAM_S task_8 = {0};
    TSK_INIT_PARAM_S task_9 = {0};
    TSK_INIT_PARAM_S task_10 = {0};
    TSK_INIT_PARAM_S task_11 = {0};

    unsigned int ret = LOS_OK;

    task_1.pfnTaskEntry = (TSK_ENTRY_FUNC)lcd_process;
    task_1.uwStackSize = 20480;
    task_1.pcName = "lcd process";
    task_1.usTaskPrio = 24;
    ret = LOS_TaskCreate(&thread_id_1, &task_1);
    if (ret != LOS_OK)
    {
        printf("Falied to create task ret:0x%x\n", ret);
        return;
    }

    task_2.pfnTaskEntry = (TSK_ENTRY_FUNC)sht30_proress;
    task_2.uwStackSize = 2048;
    task_2.pcName = "sht30 process";
    task_2.usTaskPrio = 24;
    ret = LOS_TaskCreate(&thread_id_2, &task_2);
    if (ret != LOS_OK)
    {
        printf("Falied to create task ret:0x%x\n", ret);
        return;
    }

    task_3.pfnTaskEntry = (TSK_ENTRY_FUNC)beep_process;
    task_3.uwStackSize = 2048;
    task_3.pcName = "beep_process";
    task_3.usTaskPrio = 24;
    ret = LOS_TaskCreate(&thread_id_3, &task_3);
    if (ret != LOS_OK)
    {
        printf("Falied to create task ret:0x%x\n", ret);
        return;
    }

    task_4.pfnTaskEntry = (TSK_ENTRY_FUNC)rgb_led_process;
    task_4.uwStackSize = 2048;
    task_4.pcName = "rgb_led_process";
    task_4.usTaskPrio = 24;
    ret = LOS_TaskCreate(&thread_id_4, &task_4);
    if (ret != LOS_OK)
    {
        printf("Falied to create task ret:0x%x\n", ret);
        return;
    }

    task_5.pfnTaskEntry = (TSK_ENTRY_FUNC)iot_thread;
    task_5.uwStackSize = 20480*5;
    task_5.pcName = "iot_thread";
    task_5.usTaskPrio = 24;
    ret = LOS_TaskCreate(&thread_id_5, &task_5);
    if (ret != LOS_OK)
    {
        printf("Falied to create task ret:0x%x\n", ret);
        return;
    }

    task_6.pfnTaskEntry = (TSK_ENTRY_FUNC)smart_home_thread;
    task_6.uwStackSize = 20480;
    task_6.pcName = "smart_home_thread";
    task_6.usTaskPrio = 24;
    ret = LOS_TaskCreate(&thread_id_6, &task_6);
    if (ret != LOS_OK)
    {
        printf("Falied to create task ret:0x%x\n", ret);
        return;
    }


    // 在smart_pill_box()中添加
    task_7.pfnTaskEntry = (TSK_ENTRY_FUNC)ntp_sync_task;
    task_7.uwStackSize = 2048;
    task_7.pcName = "ntp_sync";
    task_7.usTaskPrio = 24;  // 低于网络任务优先级
    ret = LOS_TaskCreate(&thread_id_7, &task_7);
    if (ret != LOS_OK) {
        printf("Falied to create task ret:0x%x\n", ret);
    }

    
    task_8.pfnTaskEntry = (TSK_ENTRY_FUNC)time_compare_thread;
    task_8.uwStackSize = 2048;
    task_8.pcName = "time_compare_thread";
    task_8.usTaskPrio = 24;
    ret = LOS_TaskCreate(&thread_id_8, &task_8);
    if (ret != LOS_OK) {
        printf("Falied to create task ret:0x%x\n", ret);
    }

    task_9.pfnTaskEntry = (TSK_ENTRY_FUNC)gas_sensor_process;
    task_9.uwStackSize = 2048;
    task_9.pcName = "gas_sensor_process";
    task_9.usTaskPrio = 24;
    ret = LOS_TaskCreate(&thread_id_9, &task_9);
    if (ret != LOS_OK) {
        printf("Falied to create task ret:0x%x\n", ret);
    }

    task_10.pfnTaskEntry = (TSK_ENTRY_FUNC)electrical_machinery_process;
    task_10.uwStackSize = 2048;
    task_10.pcName = "electrical_machinery_process";
    task_10.usTaskPrio = 24;
    ret = LOS_TaskCreate(&thread_id_10, &task_10);
    if (ret != LOS_OK) {
        printf("Falied to create task ret:0x%x\n", ret);
    }

    LOS_Msleep(20000); 
    test_udp_socket(); // 先测试 socket 是否可用
    get_ntp_time("ntp.ntsc.ac.cn");
}

APP_FEATURE_INIT(smart_pill_box);